import {createRouter, createWebHistory, type RouteRecordRaw} from 'vue-router';
import { useStore } from "@/stores";
import { loadAuthUserAsset } from '@/apis'

import LoginPage from "@/views/login/LoginPage.vue";
import UserLayout from "@/views/layouts/UserLayout.vue";

// 静态路由表
const routes: Array<RouteRecordRaw> = [
  {
    path: '/user',
    name: 'login',
    component: UserLayout,
    children: [
      {
        path: 'login',
        name: 'login',
        component: LoginPage
      }
    ]
  },
  {
    redirect: '/user/login',
    path:'/'
  }
]

// 路由对象
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  console.log('跳转页面[from、to]:', from.path, to.path);
  if (to.path === '/user/login') {
    next();
  } else {
    const store = useStore();
    if (store.hasBuildRoute()) {
      next();
    } else {
      const menuRoutes: any = store.getMenuRoute();
      console.log('跳转页面[from、to], menuRoutes:', menuRoutes);
      if (menuRoutes && menuRoutes.length > 0) {
        store.buildRoutes(menuRoutes, router);
        next({ path: to.path, replace: true })
      } else {
        next();
      }
    }
  }
})

export default router;
